<template>
  <div class="register-container">
    <div class="register-box">
      <h2 class="title">校园二手书交易平台</h2>
      
      <el-form :model="registerForm" :rules="registerRules" ref="registerForm" class="register-form">
        <el-form-item prop="username">
          <el-input 
            v-model="registerForm.username" 
            prefix-icon="el-icon-user"
            placeholder="请输入用户名">
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input 
            v-model="registerForm.password" 
            prefix-icon="el-icon-lock"
            type="password"
            placeholder="请输入密码">
          </el-input>
        </el-form-item>

        <el-form-item prop="confirmPassword">
          <el-input 
            v-model="registerForm.confirmPassword" 
            prefix-icon="el-icon-lock"
            type="password"
            placeholder="请确认密码">
          </el-input>
        </el-form-item>

        <el-form-item prop="phone">
          <el-input 
            v-model="registerForm.phone" 
            prefix-icon="el-icon-mobile-phone"
            placeholder="请输入手机号">
          </el-input>
        </el-form-item>

        <el-form-item prop="code">
          <div class="code-input">
            <el-input 
              v-model="registerForm.code" 
              prefix-icon="el-icon-message"
              placeholder="请输入验证码">
            </el-input>
            <el-button 
              type="primary" 
              :loading="loading"
              :disabled="isCodeSending || loading"
              @click="handleSendCode"
              class="code-btn">
              {{ codeButtonText }}
            </el-button>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleRegister" class="register-btn">注册</el-button>
        </el-form-item>
      </el-form>

      <div class="login-now">
        已有账号？<el-button type="text" @click="$router.push('/login')">立即登录</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'
export default {
  name: 'RegisterPage',
  data() {
    // 密码验证规则
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.registerForm.confirmPassword !== '') {
          this.$refs.registerForm.validateField('confirmPassword')
        }
        callback()
      }
    }
    // 确认密码验证规则
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.registerForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }

    return {
      registerForm: {
        username: '',
        password: '',
        confirmPassword: '',
        phone: '',
        code: ''
      },
      isCodeSending: false,
      countdown: 60,
      codeButtonText: '获取验证码',
      registerRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, validator: validatePass, trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, validator: validatePass2, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    handleRegister() {
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          // 构建注册请求数据
          const registerData = {
            username: this.registerForm.username,
            password: this.registerForm.password,
            phone: this.registerForm.phone,
            code: this.registerForm.code
          }
          
          request.post('/api/register', registerData)
            .then(res => {
              if (res.data.code === 1) {
                this.$message.success('注册成功')
                // 注册成功后跳转到登录页
                setTimeout(() => {
                  this.$router.push('/login')
                }, 1500)
              } else {
                this.$message.error(res.data.msg || '注册失败')
              }
            })
            .catch(error => {
              this.$message.error(error.response?.data?.msg || '注册失败，请稍后重试')
            })
        }
      })
    },
    handleSendCode() {
      this.$refs.registerForm.validateField('phone', (errorMessage) => {
        if (!errorMessage) {
          this.loading = true  // 开始loading
          
          request.get('/api/sms/singup/sendcode', {
            params: {
              phone: this.registerForm.phone
            }
          }).then(res => {
            if (res.data.code === 1) {
              this.$message.success('验证码发送成功')
              // 发送成功后开始倒计时
              this.isCodeSending = true
              this.countdown = 60
              this.codeButtonText = `${this.countdown}秒后重试`
              
              const timer = setInterval(() => {
                this.countdown--
                this.codeButtonText = `${this.countdown}秒后重试`
                
                if (this.countdown <= 0) {
                  clearInterval(timer)
                  this.isCodeSending = false
                  this.codeButtonText = '获取验证码'
                }
              }, 1000)
            } else {
              this.$message.error(res.data.msg || '验证码发送失败')
            }
          }).catch(error => {
            this.$message.error(error.response?.data?.msg || '验证码发送失败')
          }).finally(() => {
            this.loading = false  // 结束loading
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.code-btn {
  width: 120px;
}
.register-container {
  min-height: 100vh;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: auto;
}

.register-box {
  width: 420px;
  padding: 40px;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  margin: 20px;
  animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.title {
  text-align: center;
  margin-bottom: 30px;
  color: #303133;
  font-size: 28px;
  font-weight: 600;
  background: linear-gradient(45deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  letter-spacing: 1px;
}

.register-form {
  margin-top: 20px;
}

.register-form :deep(.el-input__inner) {
  height: 45px;
  line-height: 45px;
  border-radius: 10px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s;
  padding-left: 40px;
  font-size: 14px;
}

.register-form :deep(.el-input__inner:focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
}

.register-form :deep(.el-input__prefix) {
  left: 12px;
}

.register-form :deep(.el-input__prefix .el-input__icon) {
  font-size: 18px;
  color: #909399;
}

.register-btn {
  width: 100%;
  height: 45px;
  border-radius: 10px;
  font-size: 16px;
  font-weight: 500;
  background: linear-gradient(45deg, #667eea, #764ba2);
  border: none;
  transition: all 0.3s;
  letter-spacing: 1px;
}

.register-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.register-btn:active {
  transform: translateY(0);
}

.code-input {
  display: flex;
  gap: 12px;
}

.code-input .el-input {
  flex: 1;
}

.code-btn {
  width: 120px;
  height: 45px;
  border-radius: 10px;
  font-size: 14px;
  background: linear-gradient(45deg, #667eea, #764ba2);
  border: none;
  transition: all 0.3s;
  white-space: nowrap;
}

.code-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.code-btn:disabled {
  background: #a8b1e9;
  cursor: not-allowed;
}

.login-now {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
  color: #606266;
}

.login-now .el-button {
  font-size: 14px;
  color: #667eea;
  font-weight: 500;
  transition: all 0.3s;
}

.login-now .el-button:hover {
  color: #764ba2;
  transform: translateY(-1px);
}

/* 响应式设计 */
@media screen and (max-width: 480px) {
  .register-box {
    width: 90%;
    padding: 30px 20px;
    margin: 15px;
  }
  
  .title {
    font-size: 24px;
  }
  
  .register-form :deep(.el-input__inner) {
    height: 40px;
    line-height: 40px;
  }
  
  .register-btn, .code-btn {
    height: 40px;
  }
}
</style>